import requests
import pymysql
import json
import _thread
import time
import hashlib
import random

# ======================================================================================================================
# readme
# 操作静静的后台管理接口
# 1.可以批量注册静静的账号
# 2.可以实现修改静静的用户账号类型      批量实名认证方便开播
# 3.可以下载静静的用户数据
#
# https://htgl.cwoqu.com/api/users/updateasset 变动账户余额   减余额
# acoin: 0
# coin: " 567799397"
# gold_coin: 567799397
# head: "https://jingjing-imgs.oss-cn-chengdu.aliyuncs.com/bcb7dcd5566257d753e5ed3ba48043f9/1642739639180.jpg?Expires=1656760997&OSSAccessKeyId=LTAI5t6xscbGY1Kg33hi9vpX&Signature=5K2jbR4XO83QOXRHFnBGYwWCI4M%3D"
# nick: "这是那个的水军呢...."
# para_type: 2
# remark: "222"
# type: 2
# uid: 200122

# 静静币减少
#acoin: 909062944
#coin: "909062944"
#gold_coin: 562815
#head: "https://jingjing-imgs.oss-cn-chengdu.aliyuncs.com/688487cd117549bef083f26cad007f7d/3C1389CF-13E6-4690-B47F-9B84BE63B59F.png?Expires=1656761025&OSSAccessKeyId=LTAI5t6xscbGY1Kg33hi9vpX&Signature=xAw3tWPSLN0hgbF1CrK8AndsV8c%3D"
#nick: "杀破狼"
#para_type: 2
#remark: "减少"
#type: 1
#uid: 200108

# 静静币加
# acoin: 0
# coin: "999000000"
# gold_coin: 562815
# head: "https://jingjing-imgs.oss-cn-chengdu.aliyuncs.com/688487cd117549bef083f26cad007f7d/3C1389CF-13E6-4690-B47F-9B84BE63B59F.png?Expires=1656761165&OSSAccessKeyId=LTAI5t6xscbGY1Kg33hi9vpX&Signature=tLvKr5OfD1qPOsmSoSGbJ63FBCI%3D"
# nick: "杀破狼"
# para_type: 1
# remark: "加"
# type: 1
# uid: 200108

# acoin: 999000000
# coin: "562815"
# gold_coin: 562815
# head: "https://jingjing-imgs.oss-cn-chengdu.aliyuncs.com/688487cd117549bef083f26cad007f7d/3C1389CF-13E6-4690-B47F-9B84BE63B59F.png?Expires=1656761243&OSSAccessKeyId=LTAI5t6xscbGY1Kg33hi9vpX&Signature=V41g7jNDSDjDMgGd0zpv%2BS3lZ3s%3D"
# nick: "杀破狼"
# para_type: 2
# remark: "魅力减少"
# type: 2
# uid: 200108

# api_base_url = "http://api.qingqingzhibo.com/api/"
# base_url = "http://htgl.qingqingzhibo.com/api/"  # 332501198011270427
# Authorization = 'Bearer eyJ0eXAiOiJKV1QiLCJhbGciOiJIUzI1NiJ9.eyJVc2VySWQiOjEyNiwiVXNlck5hbWUiOiJ6aGFuZ2hvbmciLCJOYW1lIjoi5byg5rSqIiwiUGFyZW50SWQiOjAsIlBhcmVudE5hbWUiOiIiLCJCdXNpbmVzc0ZlZSI6MCwiRmVlIjowLCJSb2xlcyI6WzE2XSwiUm9sZU5hbWUiOiLlvIDlj5HkurrlkZgiLCJJc0FkbWluIjpmYWxzZSwiRXhwaXJ5RGF0ZVRpbWUiOiIyMDIyLTAyLTIxVDExOjEzOjQwLjI0NTg4MzMrMDg6MDAifQ.-F9h43IfE6tC6sytEYpzJz4DPso1wqDEDfBp6Eb30cU'
# Cookie = 'Admin-Token=eyJ0eXAiOiJKV1QiLCJhbGciOiJIUzI1NiJ9.eyJVc2VySWQiOjEyNiwiVXNlck5hbWUiOiJ6aGFuZ2hvbmciLCJOYW1lIjoi5byg5rSqIiwiUGFyZW50SWQiOjAsIlBhcmVudE5hbWUiOiIiLCJCdXNpbmVzc0ZlZSI6MCwiRmVlIjowLCJSb2xlcyI6WzE2XSwiUm9sZU5hbWUiOiLlvIDlj5HkurrlkZgiLCJJc0FkbWluIjpmYWxzZSwiRXhwaXJ5RGF0ZVRpbWUiOiIyMDIyLTAyLTIxVDExOjEzOjQwLjI0NTg4MzMrMDg6MDAifQ.-F9h43IfE6tC6sytEYpzJz4DPso1wqDEDfBp6Eb30cU; sidebarStatus=0'
# Host = 'htgl.qingqingzhibo.com'

api_base_url = "https://api.cwoqu.com/api/"
base_url = "https://htgl.cwoqu.com/api/"  # 332501198011270427
Authorization = 'Bearer eyJ0eXAiOiJKV1QiLCJhbGciOiJIUzI1NiJ9.eyJVc2VySWQiOjEyNiwiVXNlck5hbWUiOiJ6aGFuZ2hvbmciLCJOYW1lIjoi5byg5rSqIiwiUGFyZW50SWQiOjAsIlBhcmVudE5hbWUiOiIiLCJCdXNpbmVzc0ZlZSI6MCwiRmVlIjowLCJSb2xlcyI6WzE2XSwiUm9sZU5hbWUiOiLlvIDlj5HkurrlkZgiLCJJc0FkbWluIjpmYWxzZSwiRXhwaXJ5RGF0ZVRpbWUiOiIyMDIyLTA3LTE2VDEwOjM2OjEwLjE2Mjg4ODkrMDg6MDAifQ.7_wCrJpw26o4QSyuqfZ9Y-FlzbYu4d2HKZ7zSCQkyEY'
Cookie = 'Admin-Token=eyJ0eXAiOiJKV1QiLCJhbGciOiJIUzI1NiJ9.eyJVc2VySWQiOjEyNiwiVXNlck5hbWUiOiJ6aGFuZ2hvbmciLCJOYW1lIjoi5byg5rSqIiwiUGFyZW50SWQiOjAsIlBhcmVudE5hbWUiOiIiLCJCdXNpbmVzc0ZlZSI6MCwiRmVlIjowLCJSb2xlcyI6WzE2XSwiUm9sZU5hbWUiOiLlvIDlj5HkurrlkZgiLCJJc0FkbWluIjpmYWxzZSwiRXhwaXJ5RGF0ZVRpbWUiOiIyMDIyLTA3LTE2VDEwOjM2OjEwLjE2Mjg4ODkrMDg6MDAifQ.7_wCrJpw26o4QSyuqfZ9Y-FlzbYu4d2HKZ7zSCQkyEY; sidebarStatus=0'
Host = 'https://htgl.cwoqu.com/'

TokenFile = "tokenjingjingregister.txt"


# Url参数添加验证码
def get_url_yzt(account, password):
    cdt = str(round(time.time() * 1000))
    mydata = account + password + cdt
    yzt = hashlib.md5(mydata.encode(encoding='UTF-8')).hexdigest()
    s_act = account + "_" + password + "_" + yzt
    return "?act="+s_act+"&cdt="+cdt


# 有的接口需要yzt参数
def get_yzt(mydata):
    mydata = mydata + "a4be9f32637e217fb8dbbcae75759fb3"
    return hashlib.md5(mydata.encode(encoding='UTF-8')).hexdigest()


# 登录之后获取用户id
def get_uid():
    file = open(TokenFile, "r")
    fileData = file.read()
    try:
        json_to_python = json.loads(fileData)
        file.close()
        return json_to_python['Data']["uid"]
    except Exception:
        file.close()
        return ""


# 验证码
def get_code(cell):
    text = api_base_url + "yonghu/getloginsms"+"?cell="+cell + "&yzt=" + get_yzt(cell)
    response = get_html(text, "", "get")
    print(response)

def generate_random_str(randomlength=16):
  """
  生成一个指定长度的随机字符串
  """
  random_str =''
  base_str ='ABCDEFGHIGKLMNOPQRSTUVWXYZabcdefghigklmnopqrstuvwxyz0123456789'
  length =len(base_str) -1
  for i in range(randomlength):
    random_str +=base_str[random.randint(0, length)]
  return random_str

# 登录将登录数据放在文件中
# {code=1209, cell=13540124223, did=idf44ea3b7-0a06-41e6-836f-eaee573a8760, mac=9C:BC:F0:E0:08:EE,
# dev=, plat=Xiaomi_M2102J2SC, ver=30_11, sys=androidphone, sver=1.0.5, firm=Xiaomi_M2102J2SC,
# mart=android, token=, ip=192.168.124.11, source=and-0, yzt=7b53c4eda0763288b53adc021504b2a9,
# lat=30.537568, lng=104.092432, city=510100, cityname=成都市, state=510000, statename=四川省}
def login(phone, code="831246"):  # 831246 202088
    paramss = {"code": code, "cell": phone, "did": generate_random_str(),
               "mac": "3C:86:D1:5A:EB:"+str(random.randint(10,99)), "dev": "1", "plat": "vivo_V1928A", "ver": "28_9",
               "sys": "androidphone", "sver": "1.0.5", "firm": "9",
               "mart": "android", "token": "", "ip": "192.168."+str(random.randint(3, 200))+"."+str(random.randint(5, 200)), "source": "and-0",
               "yzt": get_yzt(phone), "lat": "30.554378",
               "lng": "104.07132", "city": "510100", "cityname": "成都市",
               "state": "510000", "statename": "四川省"}

    url = "http://www.siyetian.com/index/apis_get.html?token=gHbi1yTEF0MPRVR35ERjlXTn1STqFUeNpWQz0ERVBTTqlUMNp2Y59ERnNTTqVEM.AMxETMzAzN1YTM&limit=1&type=0&time=0&split=0&split_text=&area=0&repeat=0&isp="  # 代理服务器
    res = requests.get(url, timeout=5)


    dd = str(paramss)
    print("login  代理地址:"+res.text+" 参数："+dd)
    par = dd.encode("utf-8").decode("latin-1")
    data = get_html(api_base_url + "yonghu/celllogin", par, "post")
    print("=================login:"+data)
    file = open(TokenFile, "w")
    file.write(data)
    file.close()


# 注册
def register():
    paramss = {"uid": get_uid(), "head": "", "nick": "修女",
               "sex": "f", "city": "510100", "state": "510000", "asign": "", "sign": "", "back": "", "zsign": "",
               "share_code": "", "yzt": get_yzt(get_uid())}
    text = api_base_url + "yonghu/setuserinfo"
    response = get_html(text, json.dumps(paramss))
    print("========================注册结果："+response)

# APP端调用API接口html请求
def get_html(url, paramss, type="post", prox=""):
    try:
        file = open(TokenFile, "r")
        fileData = file.read()
        token = ""
        yzt = ""
        try:
            json_to_python = json.loads(fileData)
            token = json_to_python['Data']["token"]
            cell = json_to_python['Data']["cell"]
            pwd = json_to_python['Data']["password"]
            yzt = get_url_yzt(cell, pwd)
        except Exception as e1:
            print("http:================================================================json 解析出错:" + str(e1))
        file.close()
        header = {'Content-Type': 'application/json; charset=UTF-8',
                  "app_type": "1",
                  "version": "1.21.38",
                  "Authorization": token}
        # params:{uid=40076, oid=43296, key=43296, type=0, gid=43, gift_type=1, num=1, plat=android, yzt=56070fae6b37ad772ae6ed994a082038}
        # 代理
        # prox = {}

        if(len(prox)==0):
            if ("post" == type):
                url += yzt
                data = requests.post(url, data=paramss, headers=header, timeout=29)
            else:
                data = requests.get(url, data=paramss, headers=header, timeout=29)
        else:
            proxies = {
                'http': "http://"+prox,
                'https': "http://"+prox
            }
            if ("post" == type):
                print("===========================使用代理请求"+ prox)
                url += yzt
                data = requests.post(url, data=paramss, proxies=proxies, headers=header, timeout=29)
            else:
                data = requests.get(url, data=paramss, proxies=proxies, headers=header, timeout=29)
        data.encoding = "utf-8"
        return data.text
    except Exception as e:
        print(str(e))
        return "异常"


# ======================================================================================================================
# ======================================================================================================================
# ======================================================================================================================
# ======================================================================================================================
#
#                                                下面是后台接口处理
#
# ======================================================================================================================
# ======================================================================================================================
# ======================================================================================================================
# ======================================================================================================================
# ======================================================================================================================
# 获取吖咪直播所有的用户的用户数据 昵称性别
def get_index1(url, type="post", paramss=""):
    try:
        headers = {
            'Accept': 'application/json, text/plain, */*',
            'Accept - Encoding': 'gzip, deflate',
            'Accept-Language': 'zh-CN,zh;q=0.9',
            'Authorization': Authorization,
            'Cookie': Cookie,
            'referer': Host,
            # 'Host': Host,
            'User-Agent': 'Mozilla/5.0 (Linux; Android 6.0; Nexus 5 Build/MRA58N) AppleWebKit/537.36 (KHTML, '
                          'like Gecko) Chrome/90.0.4430.93 Mobile Safari/537.36',
            # 'accept-encoding': 'gzip, deflate, br',
        }
        if "post" == type:
            response = requests.post(url, data=paramss, headers=headers, timeout=39)
        else:
            response = requests.get(url, data=paramss, headers=headers, timeout=39)
        response.encoding = "utf-8"
        if response.status_code == 200:
            return response.text
    except Exception as e2:
        print('获取网页数据异常：' + str(e2))
        return None


def add_db(jsonss, str_msg):
    # 打开数据库连接，不指定数据库
    if isHome == 1:
        conn = pymysql.connect(host='localhost', user='root', password='XUHUAN.59')
    else:
        conn = pymysql.connect('localhost', 'root', 'xuhuan.5130638')
    conn.select_db('laimiao')
    cur = conn.cursor()  # 获取游标
    sunNum = 0
    try:
        # print("===========================================================================================================")
        # print(jsonss)
        jsonStr = json.loads(jsonss)
        for item in jsonStr['Data']['rows']:
            cur.execute("select * from userqq where uid=" + str(item["uid"]))
            # 使用 fetchone() 方法获取一条数据
            data = cur.fetchone()
            # print('添加语句受影响的行数：', data)
            if data is None:
                sql = "insert into userqq (uid,sex,cell,coin,gold_coin,mart,identification_name,identification_no," \
                      "spreaduid,islock,user_level,anchor_level,ip,cdt,plat,sver,register_time) " \
                      "values('{}','{}','{}','{}','{}','{}','{}','{}','{}','{}','{}','{}','{}','{}','{}','{}','{}')".format(
                    item["uid"], item["sex"], item["cell"], item["coin"], item["gold_coin"], item["mart"],
                    item["identification_name"], item["identification_no"], item["spreaduid"],
                    item["islock"], item["user_level"], item["anchor_level"], item["ip"], item["cdt"], item["plat"],
                    item["sver"], item["register_time"]
                )
                # print(len(sql))
                sunNum += cur.execute(sql)
            else:
                sql = "update userqq set uid='{}',sex='{}',cell='{}',coin='{}',gold_coin='{}',mart='{}'," \
                      "identification_name='{}'" \
                      ",identification_no='{}',spreaduid='{}',islock='{}',user_level='{}',anchor_level='{}',ip='{}'" \
                      ",cdt='{}',plat='{}',sver='{}',register_time='{}' where uid='{}'".format(
                    item["uid"], item["sex"], item["cell"], item["coin"], item["gold_coin"], item["mart"],
                    item["identification_name"], item["identification_no"], item["spreaduid"],
                    item["islock"], item["user_level"], item["anchor_level"], item["ip"], item["cdt"], item["plat"],
                    item["sver"], item["register_time"], item["uid"]
                )
                sunNum += cur.execute(sql)
            conn.commit()
    finally:
        try:
            cur.close()
            conn.close()
            print(str_msg + '  受影响的行数：' + str(sunNum))
        except Exception as e1:
            print('sql执行成功异常：' + str(e1))


def get_data(name, start, end):
    for i in range(start, end):
        try:
            # http://htgl.cwoqu.com/api/basic/forbidlist?page=1&size=20
            # print("\n\n\n\n\n\n\n\n")
            # print("========================================= 开始获取数据 =================================================")
            str_msg = "                                     " + name + "Task_Page：" + str(i)
            add_db(get_index1(base_url+"users/userlist?page=" + str(i) + "&size=20"), str_msg)
            # print("========================================= 开始获取数据 =================================================")
        except Exception as e1:
            print('循环次数 ' + str(i) + ' 异常：' + str(e1))


isHome = 1  # 公司1 家2


def get_user():
    try:
        num = 0
        xs = 100
        _thread.start_new_thread(get_data, ("Thread-1----", num, num + xs))
        _thread.start_new_thread(get_data, ("Thread-2----", num + xs * 1, num + xs * 2))
        _thread.start_new_thread(get_data, ("Thread-3----", num + xs * 2, num + xs * 3))
        # _thread.start_new_thread(get_data, ("Thread-4----", num + xs * 3, num + xs * 4))
        # _thread.start_new_thread(get_data, ("Thread-5----", num + xs * 4, num + xs * 5))
    except IOError as e:
        print("Error: 无法启动线程")
    while 1:
        pass

# 用户实名认证
def up_data_user_inf(uid, cell):
    nicks = ["旧事惘然", "归去如风", "微光倾城", "复制回忆", "似念似恋", "折现浪漫", "半夏时光", "乱世惊梦", "淡忘如思", "发酵的恋", "记忆之城", "失心之锁", "困城寄她", "流光易断", "醉歌离人", "任心自碎", "凡尘清心", "失情旧忆", "末日之泪", "思念成瘾", "沉默负荷", "不羁与醉", "浅夏韵歌", "默然等待", "晴空勿语", "瑰丽冰霜", "剩夏光年", "年少恋歌", "时光孤岛", "寻觅对半", "自以为爱", "记忆的空"]
    paramess = {
        "uid": uid,
        "yuid": uid,
        "user_type": 2,
        "cell": cell,
        "nick": nicks[random.randint(0, len(nicks)-2)],
        "sex": "女",
        # "head": "bcb7dcd5566257d753e5ed3ba48043f9/1642739639180.jpg",
        # "head_show": "http://yami-imgs.oss-cn-hangzhou.aliyuncs.com/bcb7dcd5566257d753e5ed3ba48043f9/1642739639180.jpg?Expires=1642750450&OSSAccessKeyId=LTAI4GBC6sp7xbYxujJEJmYK&Signature=5f021Jbh%2Bk1Sx1OshuC6EkZ9INc%3D",
        # "head_frond": "baf83476cbed828d8caaf67c36ee4cf2/1631012829602.png",
        # "head_frond_show": "http://yami-imgs.oss-cn-hangzhou.aliyuncs.com/baf83476cbed828d8caaf67c36ee4cf2/1631012829602.png?Expires=1642750450&OSSAccessKeyId=LTAI4GBC6sp7xbYxujJEJmYK&Signature=Asx6t7sMkeNbxZePtJEKGGZf6Y4%3D",
        "isidentity": 1,
        "identification_name": "王毅",
        "identification_no": "332501198011270427",
        # "user_level": 0,
        # "anchor_level": 0,
        # "jifen_level": 0,
        # "sign": "请成为永远疯狂永远浪漫永远清澈的存在"
    }
    print("=====================================后台实名认证=============================================")
    print(get_index1(base_url + "users/useredit", "post", paramess))

# 修改用户类型为系统账号
def change_user_type(uid, cell):
    paramess = {
        "uid": uid,
        "yuid": uid,
        "user_type": 2,
        "cell": cell,
        # "nick": "过户一个个发",
        # "head": "http://yami-imgs.oss-cn-hangzhou.aliyuncs.com/a309765c61761fd56d7f0fb5d7b44b07/1642739554412.jpg?Expires=1642750958&OSSAccessKeyId=LTAI4GBC6sp7xbYxujJEJmYK&Signature=WkQkbQxDFl%2FqSZt6mdVrUKF8jfA%3D",
        # "head_frond": "baf83476cbed828d8caaf67c36ee4cf2/1631012829602.png",
        "labour_recharge_fee": 0,
        "labour_fee": 0,
        "invite_fee": 0,
        "profit_fee": 0,
        "store_etime": "0001-01-01 00:00:00",
        "number_etime": "",
        "matchs": 0
    }
    print("=========================================后台修改账户类型=================================================================")
    print(get_index1(base_url + "users/updateusershop", "post", paramess))


user_info = {}


# 获取用户uid 和用户cell
def get_user_info():
    for i in range(221, 240):
        phone = "13540124" + str(i)
        text = get_index1(base_url + "users/userlist?page=1&size=20&cell=" + phone, "get")
        try:
            json_to_python = json.loads(text)
            # print(json_to_python['Data']['rows'][0]["uid"])
            # print(json_to_python['Data']['rows'][0]["cell"])
            user_info[phone] = json_to_python['Data']['rows'][0]["uid"]
        except IOError as e:
            print("Error: 无法启动线程")
    print(user_info)


# 查询服务器获取到验证码
def get_phone_code():
    text = get_index1(base_url + "users/yzmlist?page=1&size=20&drange[]=2021-12-31&drange[]=2023-01-27&stime=2021-12-31&etime=2023-01-27", "get")
    # print(text+"--------------------------------------------------------")
    json_to_python = json.loads(text)

    return json_to_python['Data']['rows'][0]["icode"]


# 批量注册用户接口
def register_user(): # 255
    for i in range(117, 127):
        phone = "13541111" + str(i)
        # 1.获取验证码
        get_code(phone)
        # 2.查询发送的验证码
        code = get_phone_code()
        print("==================验证码:"+code)
        time.sleep(2)
        # 3.登录/注册用户保存token 和 uid到本地
        login(phone, code)
        time.sleep(2)
        # 注册第一次会失败重复调用一次就成功了
        # login(phone, code)
        time.sleep(2)
        # 4.完善资料
        register()
        time.sleep(2)
        # 5.修改用户类型为系统用户
        change_user_type(get_uid(), phone)
        # 6.用户身份证认证
        up_data_user_inf(get_uid(), phone)


# 代理使用方法
# http://www.siyetian.com/apis.html
def getIPList():
    # 请求地址
    url = "http://www.siyetian.com/index/apis_get.html?token=gHbi1yTEF0MPRVR35ERjlXTn1STqFUeNpWQz0ERVBTTqlUMNp2Y59ERnNTTqVEM.AMxETMzAzN1YTM&limit=1&type=0&time=0&split=0&split_text=&area=0&repeat=0&isp="  # 代理服务器
    ipport = "ip:port"
    proxies = {
        'http': ipport,
        'https': ipport
    }
    res = requests.get(url, proxies=proxies, timeout=5)
    print(res.status_code)
    print(res.text)


if __name__ == '__main__':
    # 多线程下载用户数据到本地数据库
    # get_user()
    # 获取用户uid 和用户cell 方便下面修改用户的实名认证  修改用户为系统用户
    # get_user_info()
    # 修改用户为实名认证用户
    # up_data_user_inf()
    # 修改用户类型为系统用户
    # change_user_type()

    # 批量注册用户
    register_user()
    print("=============================================================执行完成=======================================")
